package com.example.palette.util;

import java.util.ArrayList;
import java.util.List;

public abstract class ObjectPool<T> {

    private Object object = new Object();
    private List<T> objectPool;
    private int maxSize;

    public ObjectPool(int maxSize) {
        this.maxSize = maxSize;
        this.objectPool = new ArrayList<>();
    }

    public T obtain() {
        synchronized (object) {
            if (objectPool.isEmpty()) {
                return generate();
            }
            return objectPool.remove(objectPool.size() - 1);
        }
    }

    public void recycle(T t) {
        synchronized (object) {
            if (objectPool.size() < maxSize) {
                objectPool.add(t);
            }
        }
    }

    public abstract T generate();
}
